import React from 'react';
import PropTypes from 'prop-types';
import { Dialog, Form, Input, Field } from '@teamix/ui';
import docs from 'utils/docs';
import intl from '../../../../../../../../../../locale';

const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {
    span: 6,
  },

  wrapperCol: {
    span: 14,
  },
};

export default class Deploykey extends React.Component {
  static propTypes = {
    trigger: PropTypes.element,
    closeModal: PropTypes.func,
    create: PropTypes.func,
  };

  static defaultProps = {
    trigger: null,
    closeModal: () => {},
  };

  constructor(props) {
    super(props);
    this.field = new Field(this);
    this.state = {
      submitting: false,
      isModalOpen: false,
    };
  }

  static getDerivedStateFromProps(props) {
    if (props.trigger) {
      return {};
    }
    return {
      isModalOpen: props.isModalOpen,
    };
  }

  showModal = () => {
    this.setState({
      isModalOpen: true,
    });
  };

  onClose = () => {
    this.setState({
      isModalOpen: false,
    });

    this.props.closeModal();
  };

  handleOk = () => {
    this.field.validate((errors) => {
      if (!errors) {
        this.setState({ submitting: true });
        const formData = this.field.getValues();
        this.props.create(formData, (isFail) => {
          if (isFail) {
            this.setState({ submitting: false });
          } else {
            this.field.reset();
            this.setState({ submitting: false });
            this.onClose();
          }
        });
      }
    });
  };

  render() {
    const { init } = this.field;

    return (
      <React.Fragment>
        {this.state.isModalOpen ? (
          <Dialog
            title={
              <div>
                {intl.get({
                  id: 'code-assets.containers.createDeploykey.CreateAKey',
                  defaultMessage: '新建密钥',
                })}
              </div>
            }
            visible
            style={{ width: '600px' }}
            onOk={this.handleOk}
            onCancel={this.onClose}
            onClose={this.onClose}
            footerActions={['cancel', 'ok']}
            okProps={{
              loading: !!this.state.submitting,
              children: intl.get({
                id: 'code-assets.containers.createDeploykey.CreateAKey',
                defaultMessage: '新建密钥',
              }),
            }}
          >
            <Form {...formItemLayout} field={this.field} labelAlign="top">
              <FormItem
                label={intl.get({
                  id: 'code-assets.containers.createDeploykey.Title',
                  defaultMessage: '标题',
                })}
                required
                {...formItemLayout}
              >
                <Input
                  autoFocus
                  placeholder={intl.get({
                    id: 'code-assets.containers.createDeploykey.EnterThePublicKeyTitle',
                    defaultMessage: '请输入公钥标题',
                  })}
                  {...init('title', {
                    rules: [
                      {
                        required: true,
                        message: intl.get({
                          id: 'code-assets.containers.createDeploykey.ThisParameterIsRequired',
                          defaultMessage: '该项为必填项',
                        }),
                      },
                    ],
                  })}
                />
              </FormItem>
              <FormItem
                {...formItemLayout}
                label={intl.get({
                  id: 'code-assets.containers.createDeploykey.PublicKey',
                  defaultMessage: '公钥',
                })}
                required
                help={
                  this.field.getState('key') === 'error' ? (
                    this.field.getError('key')
                  ) : (
                    <span>
                      {intl.get({
                        id: 'code-assets.containers.createDeploykey.TheDeploymentKeyCannotBe',
                        defaultMessage: '部署密钥不能与 SSH 密钥相同，如何生成密钥对请点击',
                      })}{' '}
                      <a
                        href={docs('sshKeyConfiguration')}
                        target="_blank"
                        rel="noopener noreferrer"
                      >
                        {intl.get({
                          id: 'code-assets.containers.createDeploykey.Here',
                          defaultMessage: '这里',
                        })}
                      </a>
                    </span>
                  )
                }
              >
                <Input.TextArea
                  placeholder={intl.get({
                    id: 'code-assets.containers.createDeploykey.PasteYourServerPublicKey',
                    defaultMessage: '请粘贴你的机器公钥',
                  })}
                  {...init('key', {
                    rules: [
                      {
                        required: true,
                        message: intl.get({
                          id: 'code-assets.containers.createDeploykey.ThisParameterIsRequired',
                          defaultMessage: '该项为必填项',
                        }),
                      },
                    ],
                  })}
                />
              </FormItem>
            </Form>
          </Dialog>
        ) : null}
        {!!this.props.trigger &&
          React.cloneElement(this.props.trigger, { onClick: this.showModal })}
      </React.Fragment>
    );
  }
}
